package com.gitee.somenvm.ninerpgitem.core.item

import com.gitee.somenvm.ninerpgitem.api.event.plugin.NineRpgItemReloadEvent
import com.gitee.somenvm.ninerpgitem.util.info
import org.bukkit.command.CommandSender
import taboolib.common.LifeCycle
import taboolib.common.platform.Awake
import taboolib.common.platform.event.SubscribeEvent
import taboolib.common.platform.function.*
import taboolib.library.configuration.ConfigurationSection
import taboolib.module.configuration.Configuration
import java.io.File
import java.util.jar.JarFile

/**
 * BY NineRpgItem
 * 物品载入骑
 *
 * @author  SomeNvM
 * @date  2023/1/16 21:31
 */
object ItemLoader {
    val configNitems = mutableListOf<NineItem>()

    val idList = mutableListOf<String>()

    @JvmStatic
    operator fun get(id: String): NineItem? {
        return configNitems.find { it.id == id }
    }

    @Awake(LifeCycle.ENABLE)
    fun load() {
        val file = File(getDataFolder(), "Item")

        if (!file.exists()) {
            JarFile(getJarFile()).entries().iterator().forEachRemaining {
                if (it.name.startsWith("Item/") && it.name.endsWith(".yml")) {
                    releaseResourceFile(it.name)
                }
            }
            info("load example item.")
            load()
            return
        }

        configNitems.clear()
        idList.clear()

        configNitems += loadItem(file)

        idList.plusAssign(configNitems.map { it.id })
        console().cast<CommandSender>()
            .info(if (configNitems.size > 0) "共加载 ${configNitems.size} 个物品" else "无物品加载")
    }

    private fun loadItem(file: File): List<NineItem> {
        return when {
            file.isDirectory -> file.listFiles()?.flatMap { loadItem(it) } ?: emptyList()
            file.extension.equals("yml", true) || file.extension.equals("yaml", true) -> {
                val config = Configuration.loadFromFile(file)
                val tempNI = mutableListOf<NineItem>()
                config.getKeys(false).forEach {
                    val temp = config.getConfigurationSection(it)
                        ?: warning("Failed to get item configuration: the value of key \"$it\" is null")
                    if (temp is ConfigurationSection) {
                        tempNI += NineItem(temp)
                    }
                }
                return tempNI
            }

            else -> emptyList()
        }
    }

    @SubscribeEvent
    fun reload(e: NineRpgItemReloadEvent.Item) {
        console().cast<CommandSender>().info("重载物品.")
        load()
    }
}